﻿using MebAppMarketplace.Biz;
using MebAppMarketplace.JsonModel;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MebAppMarketplace.Api
{
    [Route("api/[controller]/[action]")]
    public class AppController : Controller
    {
        public AppService appService { get; set; }

        /// <summary>
        /// 获取一个App列表
        /// </summary>
        /// <param name="kw"></param>
        /// <param name="category"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public JsonResult GetApps(string kw, int? category = null, int page = 1)
        {
            var list = appService.GetApps(kw, category, page);
            return this.JsonOk(list);
        }

        /// <summary>
        /// 获取推荐App
        /// </summary>
        /// <param name="page"></param>
        /// <param name="category"></param>
        /// <returns></returns>
        public JsonResult GetRecommendApps(int page = 1, int? category = null)
        {
            var list = appService.GetOfficialApps(category, page);
            return this.Json(list);
        }

        /// <summary>
        /// 获取官方App
        /// </summary>
        /// <param name="category"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public JsonResult GetOfficialApps(int? category, int page = 1)
        {
            var list = appService.GetOfficialApps(category, page);
            return this.Json(list);
        }
        /// <summary>
        /// 下载指定版本
        /// </summary>
        /// <param name="id"></param>
        /// <param name="version"></param>
        /// <returns></returns>
        public async Task Download(Guid id, int version)
        {
            string path = null;
            var state = appService.GetAppState(id, version);
            if (state == Model.AppState.Available)
            {
                path = appService.GetZipFromAppList(id, version);
                if (!System.IO.File.Exists(path))
                {
                    await this.StatusCode(404).ExecuteResultAsync(this.ControllerContext);
                }
                else
                {
                    if (await this.RangeDownload(path))
                    {
                        appService.IncreaseNDownload(state, id, version);
                    }
                }
            }
            else
            {
                await this.JsonError("发行方已阻止该应用的下载").ExecuteResultAsync(this.ControllerContext);
            }
            //return this.File(System.IO.File.OpenRead(path), "application/x-zip-compressed");
        }

        /// <summary>
        /// 获取app更新控制文件,用于安装和更新App
        /// </summary>
        /// <param name="id"></param>
        /// <param name="version"></param>
        /// <returns></returns>
        public async Task DownloadUpdateXml(Guid id, int version)
        {
            string path = null;
            var state = appService.GetAppState(id, version);
            if (state == Model.AppState.Available)
            {
                path = appService.GetAppJson(id, version);
                if (!System.IO.File.Exists(path))
                {
                    await this.StatusCode(404, path).ExecuteResultAsync(this.ControllerContext);
                }
                else
                    await this.RangeDownload(path);
            }
            else
            {
                await this.JsonError("发行方已阻止该应用的下载").ExecuteResultAsync(this.ControllerContext);
            }
        }

        /// <summary>
        /// 报告app安装事件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task AddAppInstall(Guid id)
        {
            await appService.AddAppInstall(id);
        }
        /// <summary>
        /// 报告App卸载事件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task RemoveAppInstall(Guid id)
        {
            await appService.RemoveAppInstall(id);
        }
        /// <summary>
        /// 报告App启动事件
        /// </summary>
        /// <param name="id"></param>
        /// <param name="version"></param>
        /// <returns></returns>
        public async Task IncreaseAppRun(Guid id, int version)
        {
            await appService.IncreaseNAppRun(id, version);
        }

        /// <summary>
        /// 报告App核心功能使用事件
        /// </summary>
        /// <param name="id"></param>
        /// <param name="version"></param>
        /// <returns></returns>
        public async Task IncreaseCorRun(Guid id, int version)
        {
            await appService.IncreaseNCorRun(id, version);
        }

        public JsonResult GetAppUpdates(string list)
        {
            var checkList = JsonConvert.DeserializeObject<List<CheckUpdateItem>>(list);
            return this.JsonOk(appService.GetAppUpdates(checkList));
        }

        /// <summary>
        /// 获取用户已安装的App
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<JsonResult> GetUserApp(Guid id/*AppID*/)
        {
            var userApp = await appService.GetUserApp(id);
            return this.JsonOk(userApp);
        }

        public JsonResult GetNewVersion(Guid id, int version)
        {
            return this.JsonOk(appService.GetNewVersion(id, version));
        }

        public async Task GetAppFile(Guid id, int version, string file, string hash)
        {
            string path = null;
            var state = appService.GetAppState(id, version);
            if (state == Model.AppState.Available)
            {
                path = appService.GetAppFile(id, version, file, hash);
                if (path == "404" || path == "304")
                {
                    await this.StatusCode(int.Parse(path)).ExecuteResultAsync(this.ControllerContext);
                }
                else
                {
                    await this.RangeDownload(path);
                }
            }
            else
            {
                await this.JsonError("发行方已阻止该应用的下载").ExecuteResultAsync(this.ControllerContext);
            }
        }
    }
}
